//
// In order to convert some functionality to Visual C#, the Java Language Conversion Assistant
// creates "support classes" that duplicate the original functionality.  
//
// Support classes replicate the functionality of the original code, but in some cases they are 
// substantially different architecturally. Although every effort is made to preserve the 
// original architecture of the application in the converted project, the user should be aware that 
// the primary goal of these support classes is to replicate functionality, and that at times 
// the architecture of the resulting solution may differ somewhat.
//

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;

/// <summary>
/// This interface should be implemented by any class whose instances are intended 
/// to be executed by a thread.
/// </summary>
public interface IThreadRunnable
{
    /// <summary>
    /// This method has to be implemented in order that starting of the thread causes the object's 
    /// run method to be called in that separately executing thread.
    /// </summary>
    void Run();
}

/// <summary>
/// Contains conversion support elements such as classes, interfaces and static methods.
/// </summary>
public class SupportClass
{

    public static void DumpStreamToDisk(Stream receiveStream, string encodeLabel)
    {
        Encoding encode = Encoding.GetEncoding("utf-8");

        // Pipes the stream to a higher level stream reader with the required encoding format. 
        StreamReader readStream = new StreamReader(receiveStream, encode);
        Console.WriteLine("\r\nResponse stream received.");
        Char[] read = new Char[256];
        // Reads 256 characters at a time.    
        int count = readStream.Read(read, 0, 256);
        Console.WriteLine("HTML...\r\n");
        while (count > 0)
        {
            // Dumps the 256 characters on a string and displays the string to the console.
            String str = new String(read, 0, count);
            Console.Write(str);
            count = readStream.Read(read, 0, 256);
        }
        Console.WriteLine("");

    }


    public static void CopyStream(Stream in_Renamed, Stream out_Renamed)
    {
        BinaryReader d = new BinaryReader(in_Renamed);
        try
        {
            byte buffer;
            long currentPos = 0;
            while (currentPos < in_Renamed.Length)
            {
                buffer = d.ReadByte();
                out_Renamed.WriteByte(buffer);
                currentPos++;
            }
        }
        catch (IOException) { }
    }
    /// <summary>
    /// Converts an array of sbytes to an array of bytes
    /// </summary>
    /// <param name="sbyteArray">The array of sbytes to be converted</param>
    /// <returns>The new array of bytes</returns>
    public static byte[] ToByteArray(sbyte[] sbyteArray)
    {
        byte[] byteArray = null;

        if (sbyteArray != null)
        {
            byteArray = new byte[sbyteArray.Length];
            for (int index = 0; index < sbyteArray.Length; index++)
                byteArray[index] = (byte) sbyteArray[index];
        }
        return byteArray;
    }

    /// <summary>
    /// Converts a string to an array of bytes
    /// </summary>
    /// <param name="sourceString">The string to be converted</param>
    /// <returns>The new array of bytes</returns>
    public static byte[] ToByteArray(String sourceString)
    {
        return UTF8Encoding.UTF8.GetBytes(sourceString);
    }

    /// <summary>
    /// Converts a array of object-type instances to a byte-type array.
    /// </summary>
    /// <param name="tempObjectArray">Array to convert.</param>
    /// <returns>An array of byte type elements.</returns>
    public static byte[] ToByteArray(Object[] tempObjectArray)
    {
        byte[] byteArray = null;
        if (tempObjectArray != null)
        {
            byteArray = new byte[tempObjectArray.Length];
            for (int index = 0; index < tempObjectArray.Length; index++)
                byteArray[index] = (byte) tempObjectArray[index];
        }
        return byteArray;
    }

    /*******************************/

    /// <summary>
    /// Receives a byte array and returns it transformed in an sbyte array
    /// </summary>
    /// <param name="byteArray">Byte array to process</param>
    /// <returns>The transformed array</returns>
    public static sbyte[] ToSByteArray(byte[] byteArray)
    {
        sbyte[] sbyteArray = null;
        if (byteArray != null)
        {
            sbyteArray = new sbyte[byteArray.Length];
            for (int index = 0; index < byteArray.Length; index++)
                sbyteArray[index] = (sbyte) byteArray[index];
        }
        return sbyteArray;
    }

    /*******************************/
    /*******************************/

    /// <summary>
    /// Gives support functions to Http internet connections.
    /// </summary>
    public class URLConnectionSupport
    {
        /// <summary>
        /// Sets the request property for the specified key
        /// </summary>
        /// <param name="connection">Connection used to assign the property value</param>
        /// <param name="key">Property name to obtain the property value</param>
        /// <param name="keyValue">The value to associate with the specified property</param>
        public static void SetRequestProperty(HttpWebRequest connection, String key, String keyValue)
        {
            connection.Headers.Set(key, keyValue);
        }

        /// <summary>
        /// Gets the request property for the specified key
        /// </summary>
        /// <param name="connection">Connection used to obtain the property value</param>
        /// <param name="key">Property name to return it's property value</param>
        /// <returns>The value associated with the specified property</returns>
        public static String GetRequestProperty(HttpWebRequest connection, String key)
        {
            try
            {
                return connection.Headers.Get(key);
            }
            catch (Exception)
            {
            }
            return "";
        }

        /// <summary>
        /// Receives a key and returns it's default property value
        /// </summary>
        /// <param name="key">Key name to obtain the default request value</param>
        /// <returns>The default value associated with the property</returns>
        public static String GetDefaultRequestProperty(String key)
        {
            return null;
        }

        /// <summary> 
        /// Gets the value of the "Content-Encoding" property from the collection of headers associated with the specified HttpWebRequest
        /// </summary>
        /// <param name="request">Instance of HttpWebRequest to get the headers from</param>
        /// <returns>The value of the "Content-Encoding" property if found, otherwise returns null</returns>
        public static String GetContentEncoding(HttpWebRequest request)
        {
            try
            {
                return request.GetResponse().Headers.Get("Content-Encoding");
            }
            catch (Exception)
            {
            }
            return null;
        }

        /// <summary>
        /// Gets the sending date of the resource referenced by the HttpRequest
        /// </summary>
        /// <param name="request">Instance of HttpWebRequest to get the date from</param>
        /// <returns>The sending date of the resource if found, otherwise 0</returns>
        public static long GetSendingDate(HttpWebRequest request)
        {
            long headerDate;
            try
            {
                headerDate = DateTime.Parse(request.GetResponse().Headers.Get("Date")).Ticks;
            }
            catch (Exception)
            {
                headerDate = 0;
            }
            return headerDate;
        }

        /// <summary>
        /// Gets the key for the specified index from the KeysCollection of the specified HttpWebRequest's Headers property
        /// </summary>
        /// <param name="request">Instance HttpWebRequest to get the key from</param>
        /// <param name="indexField">Index of the field to get the corresponding key</param>
        /// <returns>The key for the specified index if found, otherwise null</returns>
        public static String GetHeaderFieldKey(HttpWebRequest request, int indexField)
        {
            try
            {
                return request.GetResponse().Headers.Keys.Get(indexField);
            }
            catch (Exception)
            {
            }
            return null;
        }

        /// <summary>
        /// Gets the value of the "Last-Modified" property from the collection of headers associated with the specified HttWebRequest
        /// </summary>
        /// <param name="request">Instance of HttpWebRequest to get the headers from</param>
        /// <returns>The value of the "Last-Modified" property if found, otherwise returns null</returns>
        public static long GetLastModifiedHeaderField(HttpWebRequest request)
        {
            long fieldHeaderDate;
            try
            {
                fieldHeaderDate = DateTime.Parse(request.GetResponse().Headers.Get("Last-Modified")).Ticks;
            }
            catch (Exception)
            {
                fieldHeaderDate = 0;
            }
            return fieldHeaderDate;
        }

        /// <summary>
        /// Gets the value of the named field parsed as date in milliseconds
        /// </summary>
        /// <param name="request">Instance of System.Net.HttpWebRequest to get the headers from</param>
        /// <param name="fieldName">Name of the header field</param>
        /// <param name="defaultValue">A default value to return if the value does not exist in the headers</param>
        /// <returns></returns>
        public static long GetHeaderFieldDate(HttpWebRequest request, String fieldName, long defaultValue)
        {
            long fieldHeaderDate;
            try
            {
                fieldHeaderDate = DateTime.Parse(request.GetResponse().Headers.Get(fieldName)).Ticks;
            }
            catch (Exception)
            {
                fieldHeaderDate = defaultValue;
            }
            return fieldHeaderDate;
        }
    }

    /*******************************/

    /// <summary>
    /// Support class used to handle threads
    /// </summary>
    public class ThreadClass : IThreadRunnable
    {
        /// <summary>
        /// The instance of System.Threading.Thread
        /// </summary>
        private Thread threadField;

        /// <summary>
        /// Initializes a new instance of the ThreadClass class
        /// </summary>
        public ThreadClass()
        {
            threadField = new Thread(new ThreadStart(Run));
        }

        /// <summary>
        /// Initializes a new instance of the Thread class.
        /// </summary>
        /// <param name="Name">The name of the thread</param>
        public ThreadClass(String Name)
        {
            threadField = new Thread(new ThreadStart(Run));
            this.Name = Name;
        }

        /// <summary>
        /// Initializes a new instance of the Thread class.
        /// </summary>
        /// <param name="Start">A ThreadStart delegate that references the methods to be invoked when this thread begins executing</param>
        public ThreadClass(ThreadStart Start)
        {
            threadField = new Thread(Start);
        }

        /// <summary>
        /// Initializes a new instance of the Thread class.
        /// </summary>
        /// <param name="Start">A ThreadStart delegate that references the methods to be invoked when this thread begins executing</param>
        /// <param name="Name">The name of the thread</param>
        public ThreadClass(ThreadStart Start, String Name)
        {
            threadField = new Thread(Start);
            this.Name = Name;
        }

        /// <summary>
        /// This method has no functionality unless the method is overridden
        /// </summary>
        public virtual void Run()
        {
        }

        /// <summary>
        /// Causes the operating system to change the state of the current thread instance to ThreadState.Running
        /// </summary>
        public virtual void Start()
        {
            threadField.Start();
        }

        /// <summary>
        /// Interrupts a thread that is in the WaitSleepJoin thread state
        /// </summary>
        public virtual void Interrupt()
        {
            threadField.Interrupt();
        }

        /// <summary>
        /// Gets the current thread instance
        /// </summary>
        public Thread Instance
        {
            get { return threadField; }
            set { threadField = value; }
        }

        /// <summary>
        /// Gets or sets the name of the thread
        /// </summary>
        public String Name
        {
            get { return threadField.Name; }
            set
            {
                if (threadField.Name == null)
                    threadField.Name = value;
            }
        }

        /// <summary>
        /// Gets or sets a value indicating the scheduling priority of a thread
        /// </summary>
        public ThreadPriority Priority
        {
            get { return threadField.Priority; }
            set { threadField.Priority = value; }
        }

        /// <summary>
        /// Gets a value indicating the execution status of the current thread
        /// </summary>
        public bool IsAlive
        {
            get { return threadField.IsAlive; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether or not a thread is a background thread.
        /// </summary>
        public bool IsBackground
        {
            get { return threadField.IsBackground; }
            set { threadField.IsBackground = value; }
        }

        /// <summary>
        /// Blocks the calling thread until a thread terminates
        /// </summary>
        public void Join()
        {
            threadField.Join();
        }

        /// <summary>
        /// Blocks the calling thread until a thread terminates or the specified time elapses
        /// </summary>
        /// <param name="MiliSeconds">Time of wait in milliseconds</param>
        public void Join(long MiliSeconds)
        {
            lock (this)
            {
                threadField.Join(new TimeSpan(MiliSeconds*10000));
            }
        }

        /// <summary>
        /// Blocks the calling thread until a thread terminates or the specified time elapses
        /// </summary>
        /// <param name="MiliSeconds">Time of wait in milliseconds</param>
        /// <param name="NanoSeconds">Time of wait in nanoseconds</param>
        public void Join(long MiliSeconds, int NanoSeconds)
        {
            lock (this)
            {
                threadField.Join(new TimeSpan(MiliSeconds*10000 + NanoSeconds*100));
            }
        }

        /// <summary>
        /// Resumes a thread that has been suspended
        /// </summary>
        public void Resume()
        {
            threadField.Resume();
        }

        /// <summary>
        /// Raises a ThreadAbortException in the thread on which it is invoked, 
        /// to begin the process of terminating the thread. Calling this method 
        /// usually terminates the thread
        /// </summary>
        public void Abort()
        {
            threadField.Abort();
        }

        /// <summary>
        /// Raises a ThreadAbortException in the thread on which it is invoked, 
        /// to begin the process of terminating the thread while also providing
        /// exception information about the thread termination. 
        /// Calling this method usually terminates the thread.
        /// </summary>
        /// <param name="stateInfo">An object that contains application-specific information, such as state, which can be used by the thread being aborted</param>
        public void Abort(Object stateInfo)
        {
            lock (this)
            {
                threadField.Abort(stateInfo);
            }
        }

        /// <summary>
        /// Suspends the thread, if the thread is already suspended it has no effect
        /// </summary>
        public void Suspend()
        {
            threadField.Suspend();
        }

        /// <summary>
        /// Obtain a String that represents the current Object
        /// </summary>
        /// <returns>A String that represents the current Object</returns>
        public override String ToString()
        {
            return "Thread[" + Name + "," + Priority.ToString() + "," + "" + "]";
        }

        /// <summary>
        /// Gets the currently running thread
        /// </summary>
        /// <returns>The currently running thread</returns>
        public static ThreadClass Current()
        {
            ThreadClass CurrentThread = new ThreadClass();
            CurrentThread.Instance = Thread.CurrentThread;
            return CurrentThread;
        }
    }


    /*******************************/

    /// <summary>
    /// Provides support for ByteArrayInputStream
    /// </summary>
    public class ByteArrayInputManager
    {
        public static ByteArrayInputHashTable manager = new ByteArrayInputHashTable();

        /// <summary>
        /// A hastable to store and keep the track position
        /// </summary>
        public class ByteArrayInputHashTable : Hashtable
        {
            /// <summary>
            /// Reset the point of Read to the marked position
            /// </summary>
            /// <param name="stream">The instance of InputStream</param>
            /// <returns>The current mark position</returns>
            public long ResetMark(Stream stream)
            {
                if (this[stream] != null)
                    return ((MarkProperties) this[stream]).markposition;
                else
                    return stream.Position;
            }

            /// <summary>
            /// Marks a position into the stream
            /// </summary>
            /// <param name="index">The position that will be marked</param>
            /// <param name="stream">The stream to mark</param>
            public void MarkPosition(int index, Stream stream)
            {
                if (this[stream] == null)
                {
                    MarkProperties tempProps = new MarkProperties();
                    tempProps.markposition = stream.Position;
                    Add(stream, tempProps);
                }
                else
                {
                    ((MarkProperties) this[stream]).markposition = stream.Position;
                }
            }

            /// <summary>
            /// Returns the previously marked position of the stream or zero.
            /// </summary>
            /// <param name="stream">The stream from which the marked position is returned</param>
            /// <returns>The marked position of the specified stream or zero in case it isn't marked yet</returns>
            public int ReturnMarkPosition(Stream stream)
            {
                if (this[stream] != null)
                {
                    return (int) ((MarkProperties) this[stream]).markposition;
                }
                else
                {
                    return 0;
                }
            }

            /// <summary>
            /// Inner class. Used to have the properties of mark on .NET
            /// </summary>
            private class MarkProperties
            {
                public long markposition = 0;
            }
        }
    }

    /*******************************/

    /// <summary>
    /// Writes the exception stack trace to the received stream
    /// </summary>
    /// <param name="throwable">Exception to obtain information from</param>
    /// <param name="stream">Output sream used to write to</param>
    public static void WriteStackTrace(Exception throwable, TextWriter stream)
    {
        stream.Write(throwable.StackTrace);
        stream.Flush();
    }

    /*******************************/

    /// <summary>Reads a number of characters from the current source Stream and writes the data to the target array at the specified index.</summary>
    /// <param name="sourceStream">The source Stream to Read from.</param>
    /// <param name="target">Contains the array of characteres Read from the source Stream.</param>
    /// <param name="start">The starting index of the target array.</param>
    /// <param name="count">The maximum number of characters to Read from the source Stream.</param>
    /// <returns>The number of characters Read. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the end of the stream is reached.</returns>
    public static Int32 ReadInput(Stream sourceStream, sbyte[] target, int start, int count)
    {
        // Returns 0 bytes if not enough space in target
        if (target.Length == 0)
            return 0;

        byte[] receiver = new byte[target.Length];
        int bytesRead = sourceStream.Read(receiver, start, count);

        // Returns -1 if EOF
        if (bytesRead == 0)
            return -1;

        for (int i = start; i < start + bytesRead; i++)
            target[i] = (sbyte) receiver[i];

        return bytesRead;
    }

    /// <summary>Reads a number of characters from the current source TextReader and writes the data to the target array at the specified index.</summary>
    /// <param name="sourceTextReader">The source TextReader to Read from</param>
    /// <param name="target">Contains the array of characteres Read from the source TextReader.</param>
    /// <param name="start">The starting index of the target array.</param>
    /// <param name="count">The maximum number of characters to Read from the source TextReader.</param>
    /// <returns>The number of characters Read. The number will be less than or equal to count depending on the data available in the source TextReader. Returns -1 if the end of the stream is reached.</returns>
    public static Int32 ReadInput(TextReader sourceTextReader, sbyte[] target, int start, int count)
    {
        // Returns 0 bytes if not enough space in target
        if (target.Length == 0) return 0;

        char[] charArray = new char[target.Length];
        int bytesRead = sourceTextReader.Read(charArray, start, count);

        // Returns -1 if EOF
        if (bytesRead == 0) return -1;

        for (int index = start; index < start + bytesRead; index++)
            target[index] = (sbyte) charArray[index];

        return bytesRead;
    }

    /*******************************/

    /// <summary>
    /// SupportClass for the Stack class.
    /// </summary>
    public class StackSupport
    {
        /// <summary>
        /// Removes the element at the top of the stack and returns it.
        /// </summary>
        /// <param name="stack">The stack where the element at the top will be returned and removed.</param>
        /// <returns>The element at the top of the stack.</returns>
        public static Object Pop(ArrayList stack)
        {
            Object obj = stack[stack.Count - 1];
            stack.RemoveAt(stack.Count - 1);

            return obj;
        }
    }


    /*******************************/

    /// <summary>
    /// This method returns the literal value received
    /// </summary>
    /// <param name="literal">The literal to return</param>
    /// <returns>The received value</returns>
    public static long Identity(long literal)
    {
        return literal;
    }

    /// <summary>
    /// This method returns the literal value received
    /// </summary>
    /// <param name="literal">The literal to return</param>
    /// <returns>The received value</returns>
    public static ulong Identity(ulong literal)
    {
        return literal;
    }

    /// <summary>
    /// This method returns the literal value received
    /// </summary>
    /// <param name="literal">The literal to return</param>
    /// <returns>The received value</returns>
    public static float Identity(float literal)
    {
        return literal;
    }

    /// <summary>
    /// This method returns the literal value received
    /// </summary>
    /// <param name="literal">The literal to return</param>
    /// <returns>The received value</returns>
    public static double Identity(double literal)
    {
        return literal;
    }

    /*******************************/

    /// <summary>
    /// This class provides functionality not found in .NET collection-related interfaces.
    /// </summary>
    public class ICollectionSupport
    {
        /// <summary>
        /// Adds a new element to the specified collection.
        /// </summary>
        /// <param name="c">Collection where the new element will be added.</param>
        /// <param name="obj">Object to add.</param>
        /// <returns>true</returns>
        public static bool Add(ICollection c, Object obj)
        {
            bool added = false;
            //Reflection. Invoke either the "add" or "Add" method.


            //Get the "add" method for proprietary classes
            MethodInfo method = c.GetType().GetMethod("Add");
            if (method == null)
                method = c.GetType().GetMethod("add");
            int index = (int) method.Invoke(c, new Object[] {obj});
            if (index >= 0)
                added = true;

            return added;
        }

        /// <summary>
        /// Adds all of the elements of the "c" collection to the "target" collection.
        /// </summary>
        /// <param name="target">Collection where the new elements will be added.</param>
        /// <param name="c">Collection whose elements will be added.</param>
        /// <returns>Returns true if at least one element was added, false otherwise.</returns>
        public static bool AddAll(ICollection target, ICollection c)
        {
            IEnumerator e = new ArrayList(c).GetEnumerator();
            bool added = false;

            //Reflection. Invoke "addAll" method for proprietary classes

            MethodInfo method = target.GetType().GetMethod("addAll");

            if (method != null)
                added = (bool) method.Invoke(target, new Object[] {c});
            else
            {
                method = target.GetType().GetMethod("Add");
                while (e.MoveNext())
                {
                    bool tempBAdded = (int) method.Invoke(target, new Object[] {e.Current}) >= 0;
                    added = added ? added : tempBAdded;
                }
            }

            return added;
        }

        /// <summary>
        /// Removes all the elements from the collection.
        /// </summary>
        /// <param name="c">The collection to remove elements.</param>
        public static void Clear(ICollection c)
        {
            //Reflection. Invoke "Clear" method or "clear" method for proprietary classes
            MethodInfo method;
            try
            {
                method = c.GetType().GetMethod("Clear");

                if (method == null)
                    method = c.GetType().GetMethod("clear");

                method.Invoke(c, new Object[] {});
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// Determines whether the collection contains the specified element.
        /// </summary>
        /// <param name="c">The collection to check.</param>
        /// <param name="obj">The object to locate in the collection.</param>
        /// <returns>true if the element is in the collection.</returns>
        public static bool Contains(ICollection c, Object obj)
        {
            bool contains = false;

            //Reflection. Invoke "contains" method for proprietary classes
            MethodInfo method;
            try
            {
                method = c.GetType().GetMethod("Contains");

                if (method == null)
                    method = c.GetType().GetMethod("contains");

                contains = (bool) method.Invoke(c, new Object[] {obj});
            }
            catch (Exception e)
            {
                throw e;
            }

            return contains;
        }

        /// <summary>
        /// Determines whether the collection contains all the elements in the specified collection.
        /// </summary>
        /// <param name="target">The collection to check.</param>
        /// <param name="c">Collection whose elements would be checked for containment.</param>
        /// <returns>true id the target collection contains all the elements of the specified collection.</returns>
        public static bool ContainsAll(ICollection target, ICollection c)
        {
            IEnumerator e = c.GetEnumerator();

            bool contains = false;

            //Reflection. Invoke "containsAll" method for proprietary classes or "Contains" method for each element in the collection
            MethodInfo method;
            try
            {
                method = target.GetType().GetMethod("containsAll");

                if (method != null)
                    contains = (bool) method.Invoke(target, new Object[] {c});
                else
                {
                    method = target.GetType().GetMethod("Contains");
                    while (e.MoveNext() == true)
                    {
                        if ((contains = (bool) method.Invoke(target, new Object[] {e.Current})) == false)
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return contains;
        }

        /// <summary>
        /// Removes the specified element from the collection.
        /// </summary>
        /// <param name="c">The collection where the element will be removed.</param>
        /// <param name="obj">The element to remove from the collection.</param>
        public static bool Remove(ICollection c, Object obj)
        {
            bool changed = false;

            //Reflection. Invoke "remove" method for proprietary classes or "Remove" method
            MethodInfo method;
            try
            {
                method = c.GetType().GetMethod("remove");

                if (method != null)
                    method.Invoke(c, new Object[] {obj});
                else
                {
                    method = c.GetType().GetMethod("Contains");
                    changed = (bool) method.Invoke(c, new Object[] {obj});
                    method = c.GetType().GetMethod("Remove");
                    method.Invoke(c, new Object[] {obj});
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return changed;
        }

        /// <summary>
        /// Removes all the elements from the specified collection that are contained in the target collection.
        /// </summary>
        /// <param name="target">Collection where the elements will be removed.</param>
        /// <param name="c">Elements to remove from the target collection.</param>
        /// <returns>true</returns>
        public static bool RemoveAll(ICollection target, ICollection c)
        {
            ArrayList al = ToArrayList(c);
            IEnumerator e = al.GetEnumerator();

            //Reflection. Invoke "removeAll" method for proprietary classes or "Remove" for each element in the collection
            MethodInfo method;
            try
            {
                method = target.GetType().GetMethod("removeAll");

                if (method != null)
                    method.Invoke(target, new Object[] {al});
                else
                {
                    method = target.GetType().GetMethod("Remove");
                    MethodInfo methodContains = target.GetType().GetMethod("Contains");

                    while (e.MoveNext() == true)
                    {
                        while ((bool) methodContains.Invoke(target, new Object[] {e.Current}) == true)
                            method.Invoke(target, new Object[] {e.Current});
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }

        /// <summary>
        /// Retains the elements in the target collection that are contained in the specified collection
        /// </summary>
        /// <param name="target">Collection where the elements will be removed.</param>
        /// <param name="c">Elements to be retained in the target collection.</param>
        /// <returns>true</returns>
        public static bool RetainAll(ICollection target, ICollection c)
        {
            IEnumerator e = new ArrayList(target).GetEnumerator();
            ArrayList al = new ArrayList(c);

            //Reflection. Invoke "retainAll" method for proprietary classes or "Remove" for each element in the collection
            MethodInfo method;
            try
            {
                method = c.GetType().GetMethod("retainAll");

                if (method != null)
                    method.Invoke(target, new Object[] {c});
                else
                {
                    method = c.GetType().GetMethod("Remove");

                    while (e.MoveNext() == true)
                    {
                        if (al.Contains(e.Current) == false)
                            method.Invoke(target, new Object[] {e.Current});
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return true;
        }

        /// <summary>
        /// Returns an array containing all the elements of the collection.
        /// </summary>
        /// <returns>The array containing all the elements of the collection.</returns>
        public static Object[] ToArray(ICollection c)
        {
            int index = 0;
            Object[] objects = new Object[c.Count];
            IEnumerator e = c.GetEnumerator();

            while (e.MoveNext())
                objects[index++] = e.Current;

            return objects;
        }

        /// <summary>
        /// Obtains an array containing all the elements of the collection.
        /// </summary>
        /// <param name="objects">The array into which the elements of the collection will be stored.</param>
        /// <returns>The array containing all the elements of the collection.</returns>
        public static Object[] ToArray(ICollection c, Object[] objects)
        {
            int index = 0;

            Type type = objects.GetType().GetElementType();
            Object[] objs = (Object[]) Array.CreateInstance(type, c.Count);

            IEnumerator e = c.GetEnumerator();

            while (e.MoveNext())
                objs[index++] = e.Current;

            //If objects is smaller than c then do not return the new array in the parameter
            if (objects.Length >= c.Count)
                objs.CopyTo(objects, 0);

            return objs;
        }

        /// <summary>
        /// Converts an ICollection instance to an ArrayList instance.
        /// </summary>
        /// <param name="c">The ICollection instance to be converted.</param>
        /// <returns>An ArrayList instance in which its elements are the elements of the ICollection instance.</returns>
        public static ArrayList ToArrayList(ICollection c)
        {
            ArrayList tempArrayList = new ArrayList();
            IEnumerator tempEnumerator = c.GetEnumerator();
            while (tempEnumerator.MoveNext())
                tempArrayList.Add(tempEnumerator.Current);
            return tempArrayList;
        }
    }


    /*******************************/

    public class TransactionManager
    {
        public static ConnectionHashTable manager = new ConnectionHashTable();

        public class ConnectionHashTable : Hashtable
        {
            public OleDbCommand CreateStatement(OleDbConnection connection)
            {
                OleDbCommand command = connection.CreateCommand();
                OleDbTransaction transaction;
                if (this[connection] != null)
                {
                    ConnectionProperties Properties = ((ConnectionProperties) this[connection]);
                    transaction = Properties.Transaction;
                    command.Transaction = transaction;
                    command.CommandTimeout = 0;
                }
                else
                {
                    ConnectionProperties TempProp = new ConnectionProperties();
                    TempProp.AutoCommit = true;
                    TempProp.TransactionLevel = 0;
                    command.Transaction = TempProp.Transaction;
                    command.CommandTimeout = 0;
                    Add(connection, TempProp);
                }
                return command;
            }

            public void Commit(OleDbConnection connection)
            {
                if (this[connection] != null && !((ConnectionProperties) this[connection]).AutoCommit)
                {
                    ConnectionProperties Properties = ((ConnectionProperties) this[connection]);
                    OleDbTransaction transaction = Properties.Transaction;
                    transaction.Commit();
                    if (Properties.TransactionLevel == 0)
                        Properties.Transaction = connection.BeginTransaction();
                    else
                        Properties.Transaction = connection.BeginTransaction(Properties.TransactionLevel);
                }
            }

            public void RollBack(OleDbConnection connection)
            {
                if (this[connection] != null && !((ConnectionProperties) this[connection]).AutoCommit)
                {
                    ConnectionProperties Properties = ((ConnectionProperties) this[connection]);
                    OleDbTransaction transaction = Properties.Transaction;
                    transaction.Rollback();
                    if (Properties.TransactionLevel == 0)
                        Properties.Transaction = connection.BeginTransaction();
                    else
                        Properties.Transaction = connection.BeginTransaction(Properties.TransactionLevel);
                }
            }

            public void SetAutoCommit(OleDbConnection connection, bool boolValue)
            {
                if (this[connection] != null)
                {
                    ConnectionProperties Properties = ((ConnectionProperties) this[connection]);
                    if (Properties.AutoCommit != boolValue)
                    {
                        Properties.AutoCommit = boolValue;
                        if (!boolValue)
                        {
                            if (Properties.TransactionLevel == 0)
                                Properties.Transaction = connection.BeginTransaction();
                            else
                                Properties.Transaction = connection.BeginTransaction(Properties.TransactionLevel);
                        }
                        else
                        {
                            OleDbTransaction transaction = Properties.Transaction;
                            if (transaction != null)
                            {
                                transaction.Commit();
                            }
                        }
                    }
                }
                else
                {
                    ConnectionProperties TempProp = new ConnectionProperties();
                    TempProp.AutoCommit = boolValue;
                    TempProp.TransactionLevel = 0;
                    if (!boolValue)
                        TempProp.Transaction = connection.BeginTransaction();
                    Add(connection, TempProp);
                }
            }

            public OleDbCommand PrepareStatement(OleDbConnection connection, String sql)
            {
                OleDbCommand command = this.CreateStatement(connection);
                command.CommandText = sql;
                command.CommandTimeout = 0;
                return command;
            }

            public OleDbCommand PrepareCall(OleDbConnection connection, String sql)
            {
                OleDbCommand command = this.CreateStatement(connection);
                command.CommandText = sql;
                command.CommandTimeout = 0;
                return command;
            }

            public void SetTransactionIsolation(OleDbConnection connection, int level)
            {
                ConnectionProperties Properties;
                if (level == (int) IsolationLevel.ReadCommitted)
                    SetAutoCommit(connection, false);
                else if (level == (int) IsolationLevel.ReadUncommitted)
                    SetAutoCommit(connection, false);
                else if (level == (int) IsolationLevel.RepeatableRead)
                    SetAutoCommit(connection, false);
                else if (level == (int) IsolationLevel.Serializable)
                    SetAutoCommit(connection, false);

                if (this[connection] != null)
                {
                    Properties = ((ConnectionProperties) this[connection]);
                    Properties.TransactionLevel = (IsolationLevel) level;
                }
                else
                {
                    Properties = new ConnectionProperties();
                    Properties.AutoCommit = true;
                    Properties.TransactionLevel = (IsolationLevel) level;
                    Add(connection, Properties);
                }
            }

            public int GetTransactionIsolation(OleDbConnection connection)
            {
                if (this[connection] != null)
                {
                    ConnectionProperties Properties = ((ConnectionProperties) this[connection]);
                    if (Properties.TransactionLevel != 0)
                        return (int) Properties.TransactionLevel;
                    else
                        return 2;
                }
                else
                    return 2;
            }

            public bool GetAutoCommit(OleDbConnection connection)
            {
                if (this[connection] != null)
                    return ((ConnectionProperties) this[connection]).AutoCommit;
                else
                    return true;
            }

            /// <summary>
            /// Sets the value of a parameter using any permitted object.  The given argument object will be converted to the
            /// corresponding SQL type before being sent to the database.
            /// </summary>
            /// <param name="command">Command object to be changed.</param>
            /// <param name="parameterIndex">One-based index of the parameter to be set.</param>
            /// <param name="parameter">The object containing the input parameter value.</param>
            public void SetValue(OleDbCommand command, int parameterIndex, Object parameter)
            {
                if (command.Parameters.Count < parameterIndex)
                    command.Parameters.Add(command.CreateParameter());
                command.Parameters[parameterIndex - 1].Value = parameter;
            }

            /// <summary>
            /// Sets a parameter to SQL NULL.
            /// </summary>
            /// <param name="command">Command object to be changed.</param>
            /// <param name="parameterIndex">One-based index of the parameter to be set.</param>
            /// <param name="targetSqlType">The SQL type to be sent to the database.</param>
            public void SetNull(OleDbCommand command, int parameterIndex, int sqlType)
            {
                if (command.Parameters.Count < parameterIndex)
                    command.Parameters.Add(command.CreateParameter());
                command.Parameters[parameterIndex - 1].Value = Convert.DBNull;
                command.Parameters[parameterIndex - 1].OleDbType = (OleDbType) sqlType;
            }

            /// <summary>
            /// Sets the value of a parameter using an object.  The given argument object will be converted to the
            /// corresponding SQL type before being sent to the database.
            /// </summary>
            /// <param name="command">Command object to be changed.</param>
            /// <param name="parameterIndex">One-based index of the parameter to be set.</param>
            /// <param name="parameter">The object containing the input parameter value.</param>
            /// <param name="targetSqlType">The SQL type to be sent to the database.</param>
            public void SetObject(OleDbCommand command, int parameterIndex, Object parameter, int targetSqlType)
            {
                if (command.Parameters.Count < parameterIndex)
                    command.Parameters.Add(command.CreateParameter());
                command.Parameters[parameterIndex - 1].Value = parameter;
                command.Parameters[parameterIndex - 1].OleDbType = (OleDbType) targetSqlType;
            }

            /// <summary>
            /// Sets the value of a parameter using an object.  The given argument object will be converted to the
            /// corresponding SQL type before being sent to the database.
            /// </summary>
            /// <param name="command">Command object to be changed.</param>
            /// <param name="parameterIndex">One-based index of the parameter to be set.</param>
            /// <param name="parameter">The object containing the input parameter value.</param>
            public void SetObject(OleDbCommand command, int parameterIndex, Object parameter)
            {
                if (command.Parameters.Count < parameterIndex)
                    command.Parameters.Add(command.CreateParameter());
                command.Parameters[parameterIndex - 1].Value = parameter;
            }

            /// <summary>
            /// This method is for such prepared statements verify if the Conection is autoCommit for assing the transaction to the command.
            /// </summary>
            /// <param name="command">The command to be tested.</param>
            /// <returns>The number of rows afected.</returns>
            public int ExecuteUpdate(OleDbCommand command)
            {
                if (!(((ConnectionProperties) this[command.Connection]).AutoCommit))
                {
                    command.Transaction = ((ConnectionProperties) this[command.Connection]).Transaction;
                    return command.ExecuteNonQuery();
                }
                else
                    return command.ExecuteNonQuery();
            }

            /// <summary>
            /// This method Closes the connection, and if the property of autocommit is true make the comit operation
            /// </summary>
            /// <param name="command"> The command to be closed</param>		
            public void Close(OleDbConnection Connection)
            {
                if ((this[Connection] != null) && !(((ConnectionProperties) this[Connection]).AutoCommit))
                {
                    Commit(Connection);
                }
                Connection.Close();
            }

            private class ConnectionProperties
            {
                public bool AutoCommit;
                public OleDbTransaction Transaction;
                public IsolationLevel TransactionLevel;
            }
        }
    }


    /*******************************/

    /// <summary>
    /// This class manages the update methods of the Rowset class.
    /// </summary>
    public class UpdateReadersSupport
    {
        public static ReadersHashTable Readers = new ReadersHashTable();

        /// <summary>
        /// Manage the updates operations of Multiple OleDbDataReader.
        /// </summary>
        public class ReadersHashTable : Hashtable
        {
            /// <summary>
            /// Moves the "cursor" over the specified OleDbDataReader.
            /// </summary>
            /// <param name="reader">The reader to be set.</param>
            /// <param name="index">The new index cursor.</param>
            /// <param name="absolute">Indicates if the position is absolute or relative.</param>
            public void SetIndexRow(OleDbDataReader reader, int index, bool absolute)
            {
                ReadersProperties Properties;
                if (this[reader] != null)
                {
                    Properties = (ReadersProperties) this[reader];
                    if (absolute)
                        Properties.Row = --index;
                    else
                        Properties.Row += index;
                }
                else
                {
                    Properties = new ReadersProperties();
                    if (absolute)
                        Properties.Row = --index;
                    else
                        Properties.Row += index;
                    Add(reader, Properties);
                }
            }

            /// <summary>
            /// Indicates if the given OleDbDataReader instance is doing Insert Row operations.
            /// </summary>
            /// <param name="reader">The OleDbDataReader instance to be used.</param>
            public void SetInsertRow(OleDbDataReader reader)
            {
                ReadersProperties Properties;
                if (this[reader] != null)
                {
                    Properties = (ReadersProperties) this[reader];
                    Properties.IsInsertRow = true;
                }
                else
                {
                    Properties = new ReadersProperties();
                    Properties.IsInsertRow = true;
                    Add(reader, Properties);
                }
            }

            /// <summary>
            /// Emulates the update row operation.
            /// </summary>
            /// <param name="reader">The OleDbDataReader instance to be used.</param>
            /// <param name="column">The Column name to be modified.</param>
            /// <param name="newValue">The new value to be set.</param>
            /// <param name="connection">The database connection for the operation.</param>
            /// <param name="query">The query to be executed.</param>
            /// <param name="tableName">The table name of the operation.</param>
            public void UpdateRow(OleDbDataReader reader, String column, Object newValue, String connection,
                                  String query, String tableName)
            {
                ReadersProperties Properties;
                if (this[reader] != null)
                    Properties = (ReadersProperties) this[reader];
                else
                {
                    Properties = new ReadersProperties();
                    Add(reader, Properties);
                }
                OleDbDataAdapter tempDataAdapter = new OleDbDataAdapter(query, connection);
                OleDbCommandBuilder tempCommandBuilder = new OleDbCommandBuilder(tempDataAdapter);
                DataSet dataSet = new DataSet(tableName);
                tempDataAdapter.Fill(dataSet, tableName);
                DataTable table = dataSet.Tables[tableName];
                DataRow currentRow;
                if (Properties.IsInsertRow)
                    currentRow = table.NewRow();
                else
                    currentRow = table.Rows[Properties.Row];
                currentRow.BeginEdit();
                currentRow[column] = newValue;
                currentRow.EndEdit();
                if (Properties.IsInsertRow)
                {
                    table.Rows.Add(currentRow);
                    Properties.IsInsertRow = false;
                }
                tempDataAdapter.Update(dataSet, tableName);
            }

            /// <summary>
            /// Emulates the update row operation.
            /// </summary>
            /// <param name="reader">The OleDbDataReader instance to be used.</param>
            /// <param name="column">The column number to be modified.</param>
            /// <param name="newValue">The new value to be set.</param>
            /// <param name="connection">The database connection for the operation.</param>
            /// <param name="query">The query to be executed.</param>
            /// <param name="tableName">The table name of the operation.</param>
            public void UpdateRow(OleDbDataReader reader, int column, Object newValue, String connection, String query,
                                  String tableName)
            {
                ReadersProperties Properties;
                if (this[reader] != null)
                    Properties = (ReadersProperties) this[reader];
                else
                {
                    Properties = new ReadersProperties();
                    Add(reader, Properties);
                }
                OleDbDataAdapter tempDataAdapter = new OleDbDataAdapter(query, connection);
                OleDbCommandBuilder tempCommandBuilder = new OleDbCommandBuilder(tempDataAdapter);
                DataSet dataSet = new DataSet(tableName);
                tempDataAdapter.Fill(dataSet, tableName);
                DataTable table = dataSet.Tables[tableName];
                DataRow currentRow;
                if (Properties.IsInsertRow)
                    currentRow = table.NewRow();
                else
                    currentRow = table.Rows[Properties.Row];
                currentRow.BeginEdit();
                currentRow[column - 1] = newValue;
                currentRow.EndEdit();
                if (Properties.IsInsertRow)
                {
                    table.Rows.Add(currentRow);
                    Properties.IsInsertRow = false;
                }
                tempDataAdapter.Update(dataSet, tableName);
            }

            private class ReadersProperties
            {
                public bool IsInsertRow = false;
                public int Row = 0;
            }
        }
    }


    /*******************************/

    /// <summary>
    /// Gets the current System properties.
    /// </summary>
    /// <returns>The current system properties.</returns>
    public static NameValueCollection GetProperties()
    {
        NameValueCollection properties = new NameValueCollection();
        ArrayList keys = new ArrayList(Environment.GetEnvironmentVariables().Keys);
        ArrayList values = new ArrayList(Environment.GetEnvironmentVariables().Values);
        for (int count = 0; count < keys.Count; count++)
            properties.Add(keys[count].ToString(), values[count].ToString());
        return properties;
    }


    /*******************************/

    /// <summary>
    /// Constructs a URL from a Http Request
    /// </summary>
    /// <param name="request">Request instance</param>
    /// <returns>A string builder instance with the complete URL</returns>
    public static StringBuilder GetRequestURL(HttpRequest request)
    {
        Uri requestUrl = request.Url;
        StringBuilder returnUrl = new StringBuilder();
        returnUrl.Append(requestUrl.Scheme + "://");
        returnUrl.Append(requestUrl.Host);
        if ((requestUrl.Scheme.Equals("http") && (requestUrl.Port != 80)) ||
            (requestUrl.Scheme.Equals("https") && (requestUrl.Port != 443)))
        {
            returnUrl.Append(':' + requestUrl.Port);
        }
        returnUrl.Append(requestUrl.AbsolutePath);
        return returnUrl;
    }

    /*******************************/

    /// <summary>
    /// Represents the methods to support some operations over files.
    /// </summary>
    public class FileSupport
    {
        /// <summary>
        /// Creates a new empty file with the specified pathname.
        /// </summary>
        /// <param name="path">The abstract pathname of the file</param>
        /// <returns>True if the file does not exist and was succesfully created</returns>
        public static bool CreateNewFile(FileInfo path)
        {
            if (path.Exists)
            {
                return false;
            }
            else
            {
                FileStream createdFile = path.Create();
                createdFile.Close();
                return true;
            }
        }

        /// <summary>
        /// Compares the specified object with the specified path
        /// </summary>
        /// <param name="path">An abstract pathname to compare with</param>
        /// <param name="file">An object to compare with the given pathname</param>
        /// <returns>A value indicating a lexicographically comparison of the parameters</returns>
        public static int CompareTo(FileInfo path, Object file)
        {
            if (file is FileInfo)
            {
                FileInfo fileInfo = (FileInfo) file;
                return path.FullName.CompareTo(fileInfo.FullName);
            }
            else
            {
                throw new InvalidCastException();
            }
        }

        /// <summary>
        /// Returns an array of abstract pathnames representing the files and directories of the specified path.
        /// </summary>
        /// <param name="path">The abstract pathname to list it childs.</param>
        /// <returns>An array of abstract pathnames childs of the path specified or null if the path is not a directory</returns>
        public static FileInfo[] GetFiles(FileInfo path)
        {
            if ((path.Attributes & FileAttributes.Directory) > 0)
            {
                String[] fullpathnames = Directory.GetFileSystemEntries(path.FullName);
                FileInfo[] result = new FileInfo[fullpathnames.Length];
                for (int i = 0; i < result.Length; i++)
                    result[i] = new FileInfo(fullpathnames[i]);
                return result;
            }
            else return null;
        }

        /// <summary>
        /// Creates an instance of System.Uri class with the pech specified
        /// </summary>
        /// <param name="path">The abstract path name to create the Uri</param>
        /// <returns>A System.Uri instance constructed with the specified path</returns>
        public static Uri ToUri(FileInfo path)
        {
            UriBuilder uri = new UriBuilder();
            uri.Path = path.FullName;
            uri.Host = String.Empty;
            uri.Scheme = Uri.UriSchemeFile;
            return uri.Uri;
        }

        /// <summary>
        /// Returns true if the file specified by the pathname is a hidden file.
        /// </summary>
        /// <param name="file">The abstract pathname of the file to test</param>
        /// <returns>True if the file is hidden, false otherwise</returns>
        public static bool IsHidden(FileInfo file)
        {
            return ((file.Attributes & FileAttributes.Hidden) > 0);
        }

        /// <summary>
        /// Sets the Read-only property of the file to true.
        /// </summary>
        /// <param name="file">The abstract path name of the file to modify</param>
        public static bool SetReadOnly(FileInfo file)
        {
            try
            {
                file.Attributes = file.Attributes | FileAttributes.ReadOnly;
                return true;
            }
            catch (Exception exception)
            {
                String exceptionMessage = exception.Message;
                return false;
            }
        }

        /// <summary>
        /// Sets the last modified time of the specified file with the specified value.
        /// </summary>
        /// <param name="file">The file to change it last-modified time</param>
        /// <param name="date">Total number of miliseconds since January 1, 1970 (new last-modified time)</param>
        /// <returns>True if the operation succeeded, false otherwise</returns>
        public static bool SetLastModified(FileInfo file, long date)
        {
            try
            {
                long valueConstant = (new DateTime(1969, 12, 31, 18, 0, 0)).Ticks;
                file.LastWriteTime = new DateTime((date*10000L) + valueConstant);
                return true;
            }
            catch (Exception exception)
            {
                String exceptionMessage = exception.Message;
                return false;
            }
        }
    }

    /*******************************/

    /// <summary>
    /// The class performs token processing in strings
    /// </summary>
    public class Tokenizer : IEnumerator
    {
        /// Position over the string
        private long currentPos = 0;

        /// Include demiliters in the results.
        private bool includeDelims = false;

        /// Char representation of the String to tokenize.
        private char[] chars = null;

        //The tokenizer uses the default delimiter set: the space character, the tab character, the newline character, and the carriage-return character and the form-feed character
        private string delimiters = " \t\n\r\f";

        /// <summary>
        /// Initializes a new class instance with a specified string to process
        /// </summary>
        /// <param name="source">String to tokenize</param>
        public Tokenizer(String source)
        {
            this.chars = source.ToCharArray();
        }

        /// <summary>
        /// Initializes a new class instance with a specified string to process
        /// and the specified token delimiters to use
        /// </summary>
        /// <param name="source">String to tokenize</param>
        /// <param name="delimiters">String containing the delimiters</param>
        public Tokenizer(String source, String delimiters) : this(source)
        {
            this.delimiters = delimiters;
        }


        /// <summary>
        /// Initializes a new class instance with a specified string to process, the specified token 
        /// delimiters to use, and whether the delimiters must be included in the results.
        /// </summary>
        /// <param name="source">String to tokenize</param>
        /// <param name="delimiters">String containing the delimiters</param>
        /// <param name="includeDelims">Determines if delimiters are included in the results.</param>
        public Tokenizer(String source, String delimiters, bool includeDelims) : this(source, delimiters)
        {
            this.includeDelims = includeDelims;
        }


        /// <summary>
        /// Returns the next token from the token list
        /// </summary>
        /// <returns>The string value of the token</returns>
        public String NextToken()
        {
            return NextToken(this.delimiters);
        }

        /// <summary>
        /// Returns the next token from the source string, using the provided
        /// token delimiters
        /// </summary>
        /// <param name="delimiters">String containing the delimiters to use</param>
        /// <returns>The string value of the token</returns>
        public String NextToken(String delimiters)
        {
            //According to documentation, the usage of the received delimiters should be temporary (only for this call).
            //However, it seems it is not true, so the following line is necessary.
            this.delimiters = delimiters;

            //at the end 
            if (this.currentPos == this.chars.Length)
                throw new ArgumentOutOfRangeException();
                //if over a delimiter and delimiters must be returned
            else if ((Array.IndexOf(delimiters.ToCharArray(), chars[this.currentPos]) != -1)
                     && this.includeDelims)
                return "" + this.chars[this.currentPos++];
                //need to get the token wo delimiters.
            else
                return nextToken(delimiters.ToCharArray());
        }

        //Returns the nextToken wo delimiters
        private String nextToken(char[] delimiters)
        {
            string token = "";
            long pos = this.currentPos;

            //skip possible delimiters
            while (Array.IndexOf(delimiters, this.chars[currentPos]) != -1)
                //The last one is a delimiter (i.e there is no more tokens)
                if (++this.currentPos == this.chars.Length)
                {
                    this.currentPos = pos;
                    throw new ArgumentOutOfRangeException();
                }

            //getting the token
            while (Array.IndexOf(delimiters, this.chars[this.currentPos]) == -1)
            {
                token += this.chars[this.currentPos];
                //the last one is not a delimiter
                if (++this.currentPos == this.chars.Length)
                    break;
            }
            return token;
        }


        /// <summary>
        /// Determines if there are more tokens to return from the source string
        /// </summary>
        /// <returns>True or false, depending if there are more tokens</returns>
        public bool HasMoreTokens()
        {
            //keeping the current pos
            long pos = this.currentPos;

            try
            {
                this.NextToken();
            }
            catch (ArgumentOutOfRangeException)
            {
                return false;
            }
            finally
            {
                this.currentPos = pos;
            }
            return true;
        }

        /// <summary>
        /// Remaining tokens count
        /// </summary>
        public int Count
        {
            get
            {
                //keeping the current pos
                long pos = this.currentPos;
                int i = 0;

                try
                {
                    while (true)
                    {
                        this.NextToken();
                        i++;
                    }
                }
                catch (ArgumentOutOfRangeException)
                {
                    this.currentPos = pos;
                    return i;
                }
            }
        }

        /// <summary>
        ///  Performs the same action as NextToken.
        /// </summary>
        public Object Current
        {
            get { return this.NextToken(); }
        }

        /// <summary>
        //  Performs the same action as HasMoreTokens.
        /// </summary>
        /// <returns>True or false, depending if there are more tokens</returns>
        public bool MoveNext()
        {
            return this.HasMoreTokens();
        }

        /// <summary>
        /// Does nothing.
        /// </summary>
        public void Reset()
        {
            ;
        }
    }

    /*******************************/

    /// <summary>
    /// Obtain the query string and forms variables.
    /// </summary>
    /// <param name="QueryUser">The collection of HTTP of query string variables.</param>
    /// <param name="FormUser">The collection of forms variables.</param>
    /// <returns>Returns an enumerator that contains the query string and forms variables.</returns>
    public static IEnumerator GetParameterNames(IEnumerator QueryUser, IEnumerator FormUser)
    {
        ArrayList ArrayVariables = new ArrayList();

        while (QueryUser.MoveNext())
            if (QueryUser.Current != null)
                ArrayVariables.Add(QueryUser.Current);

        while (FormUser.MoveNext())
            if (FormUser.Current != null)
                ArrayVariables.Add(FormUser.Current);

        return ArrayVariables.GetEnumerator();
    }


    /*******************************/

    /// <summary>
    /// Interface used by classes which must be single threaded.
    /// </summary>
    public interface ISingleThreadModel
    {
    }


    /*******************************/


    public static string GetRealPath(string s, string vroot)
    {
        if ((s != null) && (s[0] == '/'))
            return "/" + vroot + s;
        else
            return s;
    }

    /*******************************/

    /// <summary>
    /// Class used to store and retrieve an object command specified as a String.
    /// </summary>
    public class CommandManager
    {
        /// <summary>
        /// Private Hashtable used to store objects and their commands.
        /// </summary>
        private static Hashtable Commands = new Hashtable();

        /// <summary>
        /// Sets a command to the specified object.
        /// </summary>
        /// <param name="obj">The object that has the command.</param>
        /// <param name="cmd">The command for the object.</param>
        public static void SetCommand(Object obj, String cmd)
        {
            if (obj != null)
            {
                if (Commands.Contains(obj))
                    Commands[obj] = cmd;
                else
                    Commands.Add(obj, cmd);
            }
        }

        /// <summary>
        /// Gets a command associated with an object.
        /// </summary>
        /// <param name="obj">The object whose command is going to be retrieved.</param>
        /// <returns>The command of the specified object.</returns>
        public static String GetCommand(Object obj)
        {
            String result = "";
            if (obj != null)
                result = Convert.ToString(Commands[obj]);
            return result;
        }
    }

    /*******************************/

    /// <summary>
    /// Implements number format functions
    /// </summary>
    [Serializable]
    public class TextNumberFormat
    {
        //Current localization number format infomation
        private NumberFormatInfo numberFormat;
        //Enumeration of format types that can be used
        private enum formatTypes
        {
            General,
            Number,
            Currency,
            Percent
        } ;

        //Current format type used in the instance
        private int numberFormatType;
        //Indicates if grouping is being used
        private bool groupingActivated;
        //Current separator used
        private String separator;
        //Number of maximun digits in the integer portion of the number to represent the number
        private int maxIntDigits;
        //Number of minimum digits in the integer portion of the number to represent the number
        private int minIntDigits;
        //Number of maximun digits in the fraction portion of the number to represent the number
        private int maxFractionDigits;
        //Number of minimum digits in the integer portion of the number to represent the number
        private int minFractionDigits;

        /// <summary>
        /// Initializes a new instance of the object class with the default values
        /// </summary>
        public TextNumberFormat()
        {
            this.numberFormat = new NumberFormatInfo();
            this.numberFormatType = (int) formatTypes.General;
            this.groupingActivated = true;
            this.separator = this.GetSeparator((int) formatTypes.General);
            this.maxIntDigits = 127;
            this.minIntDigits = 1;
            this.maxFractionDigits = 3;
            this.minFractionDigits = 0;
        }

        /// <summary>
        /// Sets the Maximum integer digits value. 
        /// </summary>
        /// <param name="newValue">the new value for the maxIntDigits field</param>
        public void setMaximumIntegerDigits(int newValue)
        {
            maxIntDigits = newValue;
            if (newValue <= 0)
            {
                maxIntDigits = 0;
                minIntDigits = 0;
            }
            else if (maxIntDigits < minIntDigits)
            {
                minIntDigits = maxIntDigits;
            }
        }

        /// <summary>
        /// Sets the minimum integer digits value. 
        /// </summary>
        /// <param name="newValue">the new value for the minIntDigits field</param>
        public void setMinimumIntegerDigits(int newValue)
        {
            minIntDigits = newValue;
            if (newValue <= 0)
            {
                minIntDigits = 0;
            }
            else if (maxIntDigits < minIntDigits)
            {
                maxIntDigits = minIntDigits;
            }
        }

        /// <summary>
        /// Sets the maximum fraction digits value. 
        /// </summary>
        /// <param name="newValue">the new value for the maxFractionDigits field</param>
        public void setMaximumFractionDigits(int newValue)
        {
            maxFractionDigits = newValue;
            if (newValue <= 0)
            {
                maxFractionDigits = 0;
                minFractionDigits = 0;
            }
            else if (maxFractionDigits < minFractionDigits)
            {
                minFractionDigits = maxFractionDigits;
            }
        }

        /// <summary>
        /// Sets the minimum fraction digits value. 
        /// </summary>
        /// <param name="newValue">the new value for the minFractionDigits field</param>
        public void setMinimumFractionDigits(int newValue)
        {
            minFractionDigits = newValue;
            if (newValue <= 0)
            {
                minFractionDigits = 0;
            }
            else if (maxFractionDigits < minFractionDigits)
            {
                maxFractionDigits = minFractionDigits;
            }
        }

        /// <summary>
        /// Initializes a new instance of the class with the specified number format
        /// and the amount of fractional digits to use
        /// </summary>
        /// <param name="theType">Number format</param>
        /// <param name="digits">Number of fractional digits to use</param>
        private TextNumberFormat(formatTypes theType, int digits)
        {
            this.numberFormat = NumberFormatInfo.CurrentInfo;
            this.numberFormatType = (int) theType;
            this.groupingActivated = true;
            this.separator = this.GetSeparator((int) theType);
            this.maxIntDigits = 127;
            this.minIntDigits = 1;
            this.maxFractionDigits = 3;
            this.minFractionDigits = 0;
        }

        /// <summary>
        /// Initializes a new instance of the class with the specified number format,
        /// uses the system's culture information,
        /// and assigns the amount of fractional digits to use
        /// </summary>
        /// <param name="theType">Number format</param>
        /// <param name="cultureNumberFormat">Represents information about a specific culture including the number formatting</param>
        /// <param name="digits">Number of fractional digits to use</param>
        private TextNumberFormat(formatTypes theType, CultureInfo cultureNumberFormat, int digits)
        {
            this.numberFormat = cultureNumberFormat.NumberFormat;
            this.numberFormatType = (int) theType;
            this.groupingActivated = true;
            this.separator = this.GetSeparator((int) theType);
            this.maxIntDigits = 127;
            this.minIntDigits = 1;
            this.maxFractionDigits = 3;
            this.minFractionDigits = 0;
        }

        /// <summary>
        /// Returns an initialized instance of the TextNumberFormat object
        /// using number representation.
        /// </summary>
        /// <returns>The object instance</returns>
        public static TextNumberFormat getTextNumberInstance()
        {
            TextNumberFormat instance = new TextNumberFormat(formatTypes.Number, 3);
            return instance;
        }

        /// <summary>
        /// Returns an initialized instance of the TextNumberFormat object
        /// using currency representation.
        /// </summary>
        /// <returns>The object instance</returns>
        public static TextNumberFormat getTextNumberCurrencyInstance()
        {
            TextNumberFormat instance = new TextNumberFormat(formatTypes.Currency, 3);
            return instance.setToCurrencyNumberFormatDefaults(instance);
        }

        /// <summary>
        /// Returns an initialized instance of the TextNumberFormat object
        /// using percent representation.
        /// </summary>
        /// <returns>The object instance</returns>
        public static TextNumberFormat getTextNumberPercentInstance()
        {
            TextNumberFormat instance = new TextNumberFormat(formatTypes.Percent, 3);
            return instance.setToPercentNumberFormatDefaults(instance);
        }

        /// <summary>
        /// Returns an initialized instance of the TextNumberFormat object
        /// using number representation, it uses the culture format information provided.
        /// </summary>
        /// <param name="culture">Represents information about a specific culture</param>
        /// <returns>The object instance</returns>
        public static TextNumberFormat getTextNumberInstance(CultureInfo culture)
        {
            TextNumberFormat instance = new TextNumberFormat(formatTypes.Number, culture, 3);
            return instance;
        }

        /// <summary>
        /// Returns an initialized instance of the TextNumberFormat object
        /// using currency representation, it uses the culture format information provided.
        /// </summary>
        /// <param name="culture">Represents information about a specific culture</param>
        /// <returns>The object instance</returns>
        public static TextNumberFormat getTextNumberCurrencyInstance(CultureInfo culture)
        {
            TextNumberFormat instance = new TextNumberFormat(formatTypes.Currency, culture, 3);
            return instance.setToCurrencyNumberFormatDefaults(instance);
        }

        /// <summary>
        /// Returns an initialized instance of the TextNumberFormat object
        /// using percent representation, it uses the culture format information provided.
        /// </summary>
        /// <param name="culture">Represents information about a specific culture</param>
        /// <returns>The object instance</returns>
        public static TextNumberFormat getTextNumberPercentInstance(CultureInfo culture)
        {
            TextNumberFormat instance = new TextNumberFormat(formatTypes.Percent, culture, 3);
            return instance.setToPercentNumberFormatDefaults(instance);
        }

        /// <summary>
        /// Clones the object instance
        /// </summary>
        /// <returns>The cloned object instance</returns>
        public Object Clone()
        {
            return this;
        }

        /// <summary>
        /// Determines if the received object is equal to the
        /// current object instance
        /// </summary>
        /// <param name="obj">TextNumber instance to compare</param>
        /// <returns>True or false depending if the two instances are equal</returns>
        public override bool Equals(Object obj)
        {
            // Check for null values and compare run-time types.
            if (obj == null || GetType() != obj.GetType())
                return false;
            TextNumberFormat param = (TextNumberFormat) obj;
            return (numberFormat == param.numberFormat) && (numberFormatType == param.numberFormatType)
                   && (groupingActivated == param.groupingActivated) && (separator == param.separator)
                   && (maxIntDigits == param.maxIntDigits) && (minIntDigits == param.minIntDigits)
                   && (maxFractionDigits == param.maxFractionDigits) && (minFractionDigits == param.minFractionDigits);
        }


        /// <summary>
        /// Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
        /// </summary>
        /// <returns>A hash code for the current Object</returns>
        public override int GetHashCode()
        {
            return numberFormat.GetHashCode() ^ numberFormatType ^ groupingActivated.GetHashCode()
                   ^ separator.GetHashCode() ^ maxIntDigits ^ minIntDigits ^ maxFractionDigits ^ minFractionDigits;
        }

        /// <summary>
        /// Formats a number with the current formatting parameters
        /// </summary>
        /// <param name="number">Source number to format</param>
        /// <returns>The formatted number string</returns>
        public String FormatDouble(double number)
        {
            if (this.groupingActivated)
            {
                return
                    SetIntDigits(
                        number.ToString(this.GetCurrentFormatString() + this.GetNumberOfDigits(number),
                                        this.numberFormat));
            }
            else
            {
                return
                    SetIntDigits(
                        (number.ToString(this.GetCurrentFormatString() + this.GetNumberOfDigits(number),
                                         this.numberFormat)).Replace(this.separator, ""));
            }
        }

        /// <summary>
        /// Formats a number with the current formatting parameters
        /// </summary>
        /// <param name="number">Source number to format</param>
        /// <returns>The formatted number string</returns>
        public String FormatLong(long number)
        {
            if (this.groupingActivated)
            {
                return
                    SetIntDigits(
                        number.ToString(this.GetCurrentFormatString() + this.minFractionDigits, this.numberFormat));
            }
            else
            {
                return
                    SetIntDigits(
                        (number.ToString(this.GetCurrentFormatString() + this.minFractionDigits, this.numberFormat)).
                            Replace(this.separator, ""));
            }
        }


        /// <summary>
        /// Formats the number according to the specified number of integer digits 
        /// </summary>
        /// <param name="number">The number to format</param>
        /// <returns></returns>
        private String SetIntDigits(String number)
        {
            String decimals;
            String fraction = "";
            int i = number.IndexOf(this.numberFormat.NumberDecimalSeparator);
            if (i > 0)
            {
                fraction = number.Substring(i);
                decimals = number.Substring(0, i).Replace(this.numberFormat.NumberGroupSeparator, "");
            }
            else decimals = number.Replace(this.numberFormat.NumberGroupSeparator, "");
            decimals = decimals.PadLeft(this.MinIntDigits, '0');
            if ((i = decimals.Length - this.MaxIntDigits) > 0) decimals = decimals.Remove(0, i);
            if (this.groupingActivated)
            {
                for (i = decimals.Length; i > 3; i -= 3)
                {
                    decimals = decimals.Insert(i - 3, this.numberFormat.NumberGroupSeparator);
                }
            }
            decimals = decimals + fraction;
            if (decimals.Length == 0) return "0";
            else return decimals;
        }

        /// <summary>
        /// Gets the list of all supported cultures
        /// </summary>
        /// <returns>An array of type CultureInfo that represents the supported cultures</returns>
        public static CultureInfo[] GetAvailableCultures()
        {
            return CultureInfo.GetCultures(CultureTypes.AllCultures);
        }

        /// <summary>
        /// Obtains the current format representation used
        /// </summary>
        /// <returns>A character representing the string format used</returns>
        private String GetCurrentFormatString()
        {
            String currentFormatString = "n"; //Default value
            switch (this.numberFormatType)
            {
                case (int) formatTypes.Currency:
                    currentFormatString = "c";
                    break;

                case (int) formatTypes.General:
                    currentFormatString = "n";
                    break;

                case (int) formatTypes.Number:
                    currentFormatString = "n";
                    break;

                case (int) formatTypes.Percent:
                    currentFormatString = "p";
                    break;
            }
            return currentFormatString;
        }

        /// <summary>
        /// Retrieves the separator used, depending on the format type specified
        /// </summary>
        /// <param name="pnumberFormatType">formatType enumarator value to inquire</param>
        /// <returns>The values of character separator used </returns>
        private String GetSeparator(int pnumberFormatType)
        {
            String separatorItem = " "; //Default Separator

            switch (pnumberFormatType)
            {
                case (int) formatTypes.Currency:
                    separatorItem = this.numberFormat.CurrencyGroupSeparator;
                    break;

                case (int) formatTypes.General:
                    separatorItem = this.numberFormat.NumberGroupSeparator;
                    break;

                case (int) formatTypes.Number:
                    separatorItem = this.numberFormat.NumberGroupSeparator;
                    break;

                case (int) formatTypes.Percent:
                    separatorItem = this.numberFormat.PercentGroupSeparator;
                    break;
            }
            return separatorItem;
        }

        /// <summary>
        /// Boolean value stating if grouping is used or not
        /// </summary>
        public bool GroupingUsed
        {
            get { return (this.groupingActivated); }
            set { this.groupingActivated = value; }
        }

        /// <summary>
        /// Minimum number of integer digits to use in the number format
        /// </summary>
        public int MinIntDigits
        {
            get { return this.minIntDigits; }
            set { this.minIntDigits = value; }
        }

        /// <summary>
        /// Maximum number of integer digits to use in the number format
        /// </summary>
        public int MaxIntDigits
        {
            get { return this.maxIntDigits; }
            set { this.maxIntDigits = value; }
        }

        /// <summary>
        /// Minimum number of fraction digits to use in the number format
        /// </summary>
        public int MinFractionDigits
        {
            get { return this.minFractionDigits; }
            set { this.minFractionDigits = value; }
        }

        /// <summary>
        /// Maximum number of fraction digits to use in the number format
        /// </summary>
        public int MaxFractionDigits
        {
            get { return this.maxFractionDigits; }
            set { this.maxFractionDigits = value; }
        }

        /// <summary>
        /// Sets the values of minFractionDigits and maxFractionDigits to the currency standard
        /// </summary>
        /// <param name="format">The TextNumberFormat instance to set</param>
        /// <returns>The TextNumberFormat with corresponding the default values</returns>
        private TextNumberFormat setToCurrencyNumberFormatDefaults(TextNumberFormat format)
        {
            format.maxFractionDigits = 2;
            format.minFractionDigits = 2;
            return format;
        }

        /// <summary>
        /// Sets the values of minFractionDigits and maxFractionDigits to the percent standard
        /// </summary>
        /// <param name="format">The TextNumberFormat instance to set</param>
        /// <returns>The TextNumberFormat with corresponding the default values</returns>
        private TextNumberFormat setToPercentNumberFormatDefaults(TextNumberFormat format)
        {
            format.maxFractionDigits = 0;
            format.minFractionDigits = 0;
            return format;
        }

        /// <summary>
        /// Gets the number of fraction digits thats must be used by the format methods
        /// </summary>
        /// <param name="number">The double number</param>
        /// <returns>The number of fraction digits to use</returns>
        private int GetNumberOfDigits(Double number)
        {
            int counter = 0;
            double temp = Math.Abs(number);
            while ((temp%1) > 0)
            {
                temp *= 10;
                counter++;
            }
            return
                (counter < this.minFractionDigits)
                    ? this.minFractionDigits
                    : ((counter < this.maxFractionDigits) ? counter : this.maxFractionDigits);
        }
    }

    /*******************************/

    public static char[] ToCharArray(byte[] bytes)
    {
        char[] charArray = null;

        if (bytes != null)
        {
            charArray = new char[bytes.Length];
            for (int index = 0; index < bytes.Length; index++)
                charArray[index] = (char) bytes[index];
        }
        return charArray;
    }
}